// index.js
// 获取应用实例
const app = getApp()
import {
  quickLogin
} from '../../apis/index';
import {
  getUserInfo
} from '../../apis/index';
import {
  getUserAssets
} from '../../apis/index.js'
Page({
  data: {
    avatarUrl: "https://profile.csdnimg.cn/4/B/D/1_qq_45959912",
    nickName: "未登录",
    yue_shuliang: '0',
    jifen_shuliang: '0',
    youhuiquan_shulaing: '0',
    token: "",
  },
  onLoad(options) {
    this.initData()
  },
  async initData() {
    const res = await getUserInfo()
    console.log("获取到的后台数据是", res)
    
    const res1 = await getUserAssets()
    console.log("获取到的后台数据是", res1)
    this.setData({
      yue_shuliang:res1.data.assets.balance,
      jifen_shuliang:res1.data.assets.points
    })
  },
  onShow() {
    const avatarUrl = wx.getStorageSync('avatarUrl')
    const nickName = wx.getStorageSync('nickName')
    const token = wx.getStorageSync('token')
    this.setData({
      avatarUrl: avatarUrl,
      nickName: nickName,
      token: token
    })
  },
  getUserProfile(e) {
    //判断是否允许使用该获取用户信息的接口
    var can = wx.canIUse('getUserProfile')
    if (!can) {
      console.log("如果不允许使用,则直接结束该行为")
      return
    }
    const _that = this
    wx.getUserProfile({
      desc: '快捷登录需要获取用户信息',
      // 获取用户信息成功之后会触发该函数
      success(result) {
        // 调用自定义的autho函数,并将用户信息传递给该函数
        _that.autho(result.userInfo)
      }
    })
  },
  async autho(userInfo) {
    const code = await this.getCode() //调用获取getCode方法用于获取code
    // 拼接要传给后台的数据
    const form = {
      'form': {
        partyData: {
          code: code,
          oauth: "MP-WEIXIN",
          userInfo: userInfo
        }
      }
    }
    const res = await quickLogin({
      data: form
    })
    console.log("快速登录的结果", res)
    if (res.status == 500) {
      console.log(form.form.partyData)
      let url = "/pages/register/index?partyData=" + encodeURIComponent(JSON.stringify(form.form.partyData))
      wx.navigateTo({
        url: url,
      })
    }
  },
  // 获取用户登录的code
  getCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          resolve(res.code)
        }
      })
    })
  },
  dingDan(){
    wx.navigateTo({
      url:'/pages/dingdan/index'
    })
  },
  gotoAddress(){
    wx.navigateTo({
      url: '/pages/user/adress/index',
    })
  }
})